package com.sandy.demo;

import com.sandy.demo.auth.*;
import com.sandy.demo.jpa.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.provisioning.InMemoryUserDetailsManagerConfigurer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AuthPermissionRepository permissionRepo;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

//        configureWeb(http);
//        configureRest(http);
        http.authorizeRequests()
                .antMatchers("/", "/**/*.js", "/**/*.css", "/**/*.html").permitAll()
                .antMatchers("/init").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }

    protected void configureWeb(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry cfg = http
                .authorizeRequests();
        cfg.antMatchers("/", "/**/*.js", "/**/*.css", "/**/*.html").permitAll();
        cfg.antMatchers("/api/init").permitAll();

        for (AuthPermission auth : permissionRepo.findAll()) {
            String[] roles = auth.getRoles().stream().map(AuthRole::getRoleId).toArray(String[]::new);
            cfg.antMatchers(auth.getUrl()).hasAnyRole(roles);
        }
        cfg.anyRequest().hasRole("ADMIN")
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }

    protected void configureRest(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers("/", "/**/*.js", "/**/*.css", "/**/*.html").permitAll()
                .antMatchers("/api/init").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
        http
                .addFilterAfter(restAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilterAfter(restTokenValidationFilter(), AnonymousAuthenticationFilter.class);

        // 禁用缓存
        http.headers().cacheControl();
    }
//    public void configure(AuthenticationManagerBuilder auth) throws Exception {
//        //inMemoryAuthentication 从内存中获取
//        auth.inMemoryAuthentication()
//                .passwordEncoder(passwordEncoder())
//                .withUser("user")
//                .password(passwordEncoder().encode("123456"))
//                .roles("ADMIN");
//    }

//    @Bean
//    public UserDetailsService getUserDetailsManager() {
//        InMemoryUserDetailsManagerConfigurer config = new InMemoryUserDetailsManagerConfigurer<>();
//        config.withUser("user").password(passwordEncoder().encode("123456"))
//                .roles("ADMIN");
//        return config.getUserDetailsService();
//    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public RestAuthenticationFilter restAuthenticationFilter() throws Exception {
        RestAuthenticationFilter bean = new RestAuthenticationFilter();
        bean.setAuthenticationManager(authenticationManager());
        bean.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler());
        bean.setAuthenticationFailureHandler(restAuthenticationFailureHandler());
        return bean;
    }

    public RestTokenValidationFilter restTokenValidationFilter() {
        RestTokenValidationFilter bean = new RestTokenValidationFilter();
        bean.setRestAuthenticationProvider(restAuthenticationProvider());
        bean.setAuthenticationSuccessHandler(restAuthenticationSuccessHandler());
        bean.setAuthenticationFailureHandler(restAuthenticationFailureHandler());
        return bean;
    }

    public RestAuthenticationProvider restAuthenticationProvider() {
        return new RestAuthenticationProvider();
    }

    public RestLogoutFilter restLogoutFilter() {
        RestLogoutFilter bean = new RestLogoutFilter();

        return bean;
    }

    RestAuthenticationSuccessHandler restAuthenticationSuccessHandler() {
        return new RestAuthenticationSuccessHandler();
    }

    RestAuthenticationFailureHandler restAuthenticationFailureHandler() {
        return new RestAuthenticationFailureHandler();
    }
}